package de.java.shortys.myhome.api.controller;

import static de.java.shortys.myhome.viewconfigurator.configuration.ViewConfigurationConstants.SWINGAPPLICATIONVIEW_TOOLBAR_FOREGROUND;
import static de.java.shortys.myhome.viewconfigurator.controller.ViewConfigurationManager.getInstance;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashSet;
import java.util.Set;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;

import de.java.shortys.myhome.api.controller.navigation.NavigationController;
import de.java.shortys.myhome.api.view.SwingApplicationView;

public abstract class AbstractSwingApplicationController {

	private SwingApplicationView view = new SwingApplicationView();

	private Set<AbstractSwingModuleController> moduleControllerList = new HashSet<AbstractSwingModuleController>();

	{
		initialize();
	}

	public void add(AbstractSwingModuleController controller) {
		moduleControllerList.add(controller);
		final JButton button = new JButton(controller.getTitle());
		addActionListener(controller, button);
		addLookAndFeel(button);
		view.add(button);

		if (!controller.allowDeactivate()) {
			controller.activate();
		}
	}

	public abstract NavigationController getNavigationController();

	private void addLookAndFeel(JButton button) {
		button.setForeground(getInstance().getColor(SWINGAPPLICATIONVIEW_TOOLBAR_FOREGROUND));
		button.setBackground(null);
		button.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7));
	}

	private void addActionListener(final AbstractSwingModuleController controller, final JButton button) {
		button.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				controller.activate();
			}
		});
	}

	public SwingApplicationView getView() {
		return view;
	}

	protected abstract void exitApplication();

	private void initialize() {
		JFrame frame = (JFrame) view.build();
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				exitApplication();
			}
		});
		frame.setVisible(true);
	}

}
